package com.ckzp.jfinal.form;

import com.alibaba.fastjson.JSON;
import com.ckzp.jfinal.plugins.tree.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 51594 on 2022/7/27.
 */
public class FormData {

    public static FormData dao() {
        return new FormData();
    }

    public static FormData n() {
        return new FormData();
    }


    /**
     * 表单类型
     * ADD
     * EDIT
     * DEL
     */
    public String actions = "EDIT";
    public String key = "";
    public boolean edit = false;
    /**
     * json数据
     */
    public Map<String, Object> json = new HashMap<String, Object>();

    /**
     * 选择框
     */
    public Map select = new HashMap();
    //传送数据
    public Map data = new HashMap();

    public String getActions() {
        return actions;
    }

    public FormData setActions(String actions) {
        this.actions = actions;
        if ("EDIT".equals(actions)) this.edit = true;
        return this;
    }

    public FormData addSelect(String name, String value) {
        this.select.put(name, value);
        return this;
    }

    public FormData addData(String name, String value) {
        this.data.put(name, value);
        return this;
    }

    public FormData addData(String name, Object value) {
        this.data.put(name, value);
        return this;
    }

    public FormData addJson(String name, Object jsons) {
        this.json.put(name, jsons);
        return this;
    }


    public FormData setKey(String key) {
        this.key = key;
        return this;
    }


    public FormData setKey(int key) {
        this.key = String.valueOf(key);
        return this;
    }

    public FormData setDefault(TreeNode node) {
        this.addData("def_id", node.getDatas().get("def_id"));
        this.addData("def_title", node.getDatas().get("def_title"));
        return this;
    }

    public Object getSelect(String name) {
        return select.get(name);
    }


    /**
     * @return
     */
    public String getAlljson() {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> entry : json.entrySet()) {
            sb.append(" var " + entry.getKey() + "=");
            sb.append(JSON.toJSONString(entry.getValue()) + ";\r\n");
        }
        return sb.toString();
    }

    /**
     * @return
     */
    public String getJson(String name) {
        StringBuffer sb = new StringBuffer();
        Object value = json.get(name);
        sb.append(" var " + name + "=");
        sb.append(JSON.toJSONString(value) + ";\r\n");
        return sb.toString();
    }

    public String toJson() {
        return JSON.toJSONString(this);
    }
}
